# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: jhkim

import os
import pandas
from absl import app, flags
from cc.appcoin2.strategy.sim_driver import batch_local, batch_slurm


def gen_important():
  rets = []
  for coin in ["BTC", "EOS", "ETH", "XRP", "LTC", "BCHABC"]:
    rets += [
        ("Futures.Huobi.v1", "realtime_light_bbo", f"{coin}-USD.QUARTER"),
        ("Futures.Huobi.v1-swap", "realtime_light_bbo", f"{coin}-USD.PERPETUAL"),
        ("Futures.Okex.v3", "realtime_light_bbo", f"{coin}-USD.QUARTER"),
        ("Futures.Okex.v3-swap", "realtime_light_bbo", f"{coin}-USD.PERPETUAL"),
        ("Futures.Binance.v1-delivery", "l1_realtime", f"{coin}-USD.QUARTER"),
        ("Futures.Binance.v1", "realtime_light_bbo", f"{coin}-USDT.PERPETUAL"),
        ("Futures.Binance.v1", "l1_realtime", f"{coin}-USDT.PERPETUAL")]
  return rets


def main(_):
  tds = flags.FLAGS.trading_date.split("-")
  if len(tds) == 1:
    tds.append(tds[0])
  dts = pandas.date_range(*tds).strftime("%Y%m%d").astype(int)
  window_size_sec = flags.FLAGS.window_size_sec
  threshold_sec = flags.FLAGS.threshold_sec
  result_dir = flags.FLAGS.sim_result_dir

  cmds = []
  for dti in dts:
    pic_dir = os.path.join(result_dir, 'pic', str(dti))
    os.makedirs(pic_dir, exist_ok=True)
    for machine in [
        "feed-01.ap-northeast-1.aws.huobi",
        "feed-05.ap-northeast-1.aws",
        "feed-05.cn-hongkong.aliyun",
        "feed-02.eu-west-1.aws",
        "feed-02.us-east-1.aws",
        "feed-02.ap-northeast-2.aws",
        "feed-02.ap-east-1.aws",
    ]:
      for worker in [0, 1, 2]:
        for mea, recipe, symbol in gen_important():
          cmd = (f"../coin_binary/coin2-bazel-bin/cc/appcoin2/support/feed/delay_detect"
                 f" --date={dti} "
                 f" --mea={mea} --recipe={recipe} --symbol={symbol} --duration=PT24H "
                 f" --threshold_sec={threshold_sec} "
                 f" --window_size_sec={window_size_sec} "
                 f" --machine={machine} "
                 f" --worker={worker}"
                 f" --out_file={pic_dir}/{dti}_{machine}_{worker}_{mea}_{recipe}_{symbol}.png &> /dev/null")  # noqa: E501
          cmds.append(cmd)

  os.makedirs("pic_detect", exist_ok=True)
  if flags.FLAGS.slurm_cpu is not None:
    tmp_dir = os.path.join(result_dir, 'tmp')
    os.makedirs(tmp_dir, exist_ok=True)
    batch_slurm(cmds, tmp_dir, flags.FLAGS.slurm_cpu)
  if flags.FLAGS.cpu is not None:
    batch_local(cmds, flags.FLAGS.cpu)


if __name__ == '__main__':
  flags.DEFINE_string('trading_date', None, '')
  flags.DEFINE_string('threshold_sec', '0.15', '')
  flags.DEFINE_string('window_size_sec', '60', '')
  flags.DEFINE_string('debug', None, '')
  flags.DEFINE_string('sim_result_dir', 'pic_detect', '')
  flags.DEFINE_integer('slurm_cpu', None, None)
  flags.DEFINE_integer('cpu', 20, None)
  app.run(main)
